<template>
  <div class="user-product">
    <!-- 搜索表单 -->
    <el-form :inline="true">
      <el-form-item>
        <el-input
          :clearable="true"
          placeholder="输入账号进行搜索"
          :prefix-icon="Search"
          @change="searchAdmin"
          v-model="searchValue"
        ></el-input>
      </el-form-item>
      <el-form-item style="text-align: right">
        <el-button type="primary" size="default" @click="addAdminOpen">添加消息管理员</el-button>
      </el-form-item>
    </el-form>
    <!-- 主体表格 -->
    <div class="table">
      <el-table :data="productAdminList" :border="true">
        <el-table-column min-width="100" align="center" type="index" width="55" />
        <el-table-column
          min-width="100"
          align="center"
          type="default"
          prop="account"
          label="账号"
        />
        <el-table-column min-width="100" align="center" type="default" prop="name" label="姓名" />
        <el-table-column
          min-width="100"
          align="center"
          type="default"
          prop="department"
          label="部门"
        />
        <el-table-column min-width="180" align="center" type="default" prop="email" label="邮箱" />
        <el-table-column min-width="160" align="center" type="default" label="操作">
          <template v-slot="{ row }">
            <el-button type="success" size="default" @click="editUser(row)">编辑</el-button>
            <el-popconfirm
              :title="`你确定要将 ${row.name} 降职为普通用户吗`"
              confirm-button-text="确认"
              cancel-button-text="取消"
              @confirm="deleteUser(row)"
              width="250px"
            >
              <template #reference>
                <el-button type="primary" size="default">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器 -->
      <div class="pagination">
        <el-pagination
          class="pagination"
          v-model:current-page="page"
          :page-size="10"
          layout="prev, pager, next, jumper,total"
          :total="total"
        />
      </div>
    </div>
  </div>
  <!-- 修改弹窗 -->
  <el-dialog
    @close="close"
    class="dialog"
    v-model="addAdminDialog"
    width="35%"
    :title="add ? '添加消息管理员' : '更新消息管理员'"
  >
    <el-form ref="addAdminRef" :model="addAdmin" class="form" :rules="rules">
      <el-form-item label="账号" prop="account">
        <el-input v-model="addAdmin.account" :disabled="!add"></el-input>
      </el-form-item>
      <el-form-item v-if="add" label="密码" prop="password">
        <el-input v-model="addAdmin.password"></el-input>
      </el-form-item>
      <el-form-item label="姓名" prop="name">
        <el-input v-model="addAdmin.name"></el-input>
      </el-form-item>
      <el-form-item label="性别" prop="sex">
        <el-select v-model="addAdmin.sex">
          <el-option value="男" :key="addAdmin.sex" label="男"></el-option>
          <el-option value="女" :key="addAdmin.sex" label="女"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="部门" prop="department">
        <el-select v-model="addAdmin.department">
          <el-option v-for="item in Department" :key="item" :value="item" :label="item"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="addAdmin.email"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button type="primary" size="default" @click="addAdminsubmit">确认</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import {
  addAdminAPI,
  getAdminListAPI,
  getDepartmentAPI,
  SearchUserAPI,
  updateAdminAPI,
  updateIdentityAPI
} from '@/api/userAdmin'
import { tracking } from '@/utils/operation'
import { Search } from '@element-plus/icons-vue'
import { ElMessage, type FormRules } from 'element-plus'
import { onMounted, reactive, ref, watch } from 'vue'
const userInfo = JSON.parse(localStorage.getItem('UserInfo')!).UserInfo

// 分页器数据
const page = ref<number>(1)
const total = ref<number>()
// 搜索Change回调
const searchValue = ref<number>()
const searchAdmin = async () => {
  if (!searchValue.value) {
    return getProductAdminList()
  }
  const res = await SearchUserAPI(searchValue.value as number, '消息管理员')
  productAdminList.value = res.data!
}
// 获取消息管理员
const productAdminList = ref<AdminInfo[]>([])
const getProductAdminList = async () => {
  const res: any = await getAdminListAPI('消息管理员', page.value)
  total.value = res.total
  productAdminList.value = res.data
}
// 弹窗操作
const addAdminDialog = ref<boolean>(false)
const addAdminOpen = () => {
  addAdminDialog.value = true
  add.value = true
}
const close = () => {
  addAdminRef.value?.resetFields()
  Object.assign(addAdmin, {
    account: null,
    password: '',
    name: '',
    sex: null,
    department: '',
    email: ''
  })
}
// 区分添加/更新
const add = ref<boolean>(true)
// 获取表单实例
const addAdminRef = ref()
// 表单校验
const rules = reactive<FormRules<UserAdmin>>({
  account: [{ required: true, message: '请输入账号', trigger: 'blur' }],
  password: [
    {
      required: true,
      message: '请输入密码',
      trigger: 'blur'
    }
  ],
  name: [
    {
      required: true,
      message: '请输入姓名',
      trigger: 'blur'
    }
  ],
  sex: [
    {
      required: true,
      message: '请输入性别',
      trigger: 'blur'
    }
  ],
  department: [
    {
      required: true,
      message: '请输入部门',
      trigger: 'blur'
    }
  ],
  email: [
    {
      required: true,
      message: '请输入邮箱',
      trigger: 'blur'
    }
  ]
})
// 添加消息管理员数据
const addAdmin = reactive<UserAdmin>({
  account: null,
  password: '',
  name: '',
  sex: null,
  department: '',
  email: ''
})
// 编辑
const editUser = (row: AdminInfo) => {
  add.value = false
  Object.assign(addAdmin, row)
  addAdminDialog.value = true
}
// 删除
const deleteUser = async (row: AdminInfo) => {
  await updateIdentityAPI(row.id, '用户')
  ElMessage({ type: 'success', message: '降职成功' })
  /** 记录操作 */
  tracking('管理员', userInfo?.name, row.name!, '高级', `降职`)
  getProductAdminList()
}
// 添加/编辑 消息管理员提交
const addAdminsubmit = async () => {
  await addAdminRef.value.validate()
  if (add.value) {
    await addAdminAPI(addAdmin, '消息管理员')
    ElMessage({ type: 'success', message: '添加成功' })
    /** 记录操作 */
    tracking('管理员', userInfo?.name, addAdmin.name!, '高级', `添加`)
  } else {
    await updateAdminAPI(addAdmin)
    ElMessage({ type: 'success', message: '更新成功' })
    /** 记录操作 */
    tracking('管理员', userInfo?.name, addAdmin.name!, '高级', `编辑`)
  }
  await getProductAdminList()
  addAdminDialog.value = false
}
const Department = ref<string[]>([])
const getDepartment = async () => {
  const res = await getDepartmentAPI()
  Department.value = JSON.parse(res.data!)
}

watch(page, () => {
  if (searchValue.value) {
    searchAdmin()
    return
  }
  getProductAdminList()
})

onMounted(() => {
  getProductAdminList()
  getDepartment()
})
</script>

<style scoped lang="scss">
.user-product {
  padding: 8px;
  .el-form {
    display: flex;
    justify-content: space-between;
    .el-form-item {
      margin: 0;
    }
  }
  .table {
    margin-top: 10px;
    .pagination {
      display: flex;
      justify-content: center;
      margin: 15px;
    }
  }
}
.form {
  max-width: 50%;
  margin: 20px auto;
}
</style>
